#include "ids.h"
#include "classes.h"
#include "drawobs.h"
#include "drawpnl.h"
#include "cfgmgr.h"
#include "drawtagwin.h"

DrawTagWindow::DrawTagWindow(DrawPanel *draw_panel, wxWindow *parent, TagManager *tag_manager) :
	wxDialog(NULL, wxID_ANY, _("Tags"), wxDefaultPosition, wxSize(200, 250), wxDEFAULT_DIALOG_STYLE | wxDIALOG_NO_PARENT | wxSTAY_ON_TOP), m_tag_manager(tag_manager)
{
	this->draw_panel = draw_panel;
	wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);

	scrolled = new wxScrolledWindow(this);
	scrolledSizer = new wxFlexGridSizer(1, wxSize(5, 5));

	auto tags = m_tag_manager->GetAllTags();
	auto valid_tags = m_tag_manager->GetGlobalValidTags();
	for( const auto& tag : tags )
	{
		bool checked = valid_tags.find(tag) != valid_tags.end();
		AddTagCheckbox(tag, checked);
	}

	AddTagCheckbox(m_tag_manager->NONE_TAG, m_tag_manager->IsParamWithoutTagsValid());
	AddTagCheckbox(m_tag_manager->ALL_TAG, m_tag_manager->IsEveryParamValid());


	auto button_sizer = new wxBoxSizer(wxHORIZONTAL);
	{
		auto ok_button = new wxButton(this, 0, _("OK"));
		ok_button->Bind(wxEVT_BUTTON, &DrawTagWindow::OnOK, this);

		auto cancel_button = new wxButton(this, 0, _("Cancel"));
		cancel_button->Bind(wxEVT_BUTTON, &DrawTagWindow::OnCancel, this);

		button_sizer->Add(ok_button, wxID_ANY, wxEXPAND);
		button_sizer->Add(cancel_button, wxID_ANY, wxEXPAND);
	}

	scrolled->SetSizer(scrolledSizer);
	scrolled->FitInside();
	scrolled->SetScrollRate(25, 25);
	mainSizer->Add(scrolled, 1, wxEXPAND);

	mainSizer->Add(button_sizer, 0, wxEXPAND | wxALL);

	SetSizer(mainSizer);
}

void DrawTagWindow::AddTagCheckbox(const std::string& tag, bool checked)
{
	auto checkbox = new wxCheckBox(scrolled, 0, tag);
	scrolledSizer->Add(checkbox, wxEXPAND);
	tag_checkboxes.push_back(checkbox);
	checkbox->SetValue(checked);
	if( checked ) {
		starting_checkboxes.push_back(tag);
	}
}

void DrawTagWindow::OnOK(wxCommandEvent& evt)
{
	std::vector<std::string> new_tags;
	for( const auto& checkbox : tag_checkboxes )
	{
		if(checkbox->IsChecked()) {
			new_tags.push_back(checkbox->GetLabel().ToStdString());
		}
	}

	m_tag_manager->ResetGlobalTags(new_tags);
	bool result = draw_panel->ReloadConfiguration();
	if( result ) {
		this->Close();
		return;
	}

	wxMessageDialog dlg(this,_("No configuration with valid sets. Resetting tags to previous state."),_("No valid tags"),
			wxOK | wxICON_ERROR);
	dlg.ShowModal();
	m_tag_manager->ResetGlobalTags( starting_checkboxes );
}

void DrawTagWindow::OnCancel(wxCommandEvent& evt)
{
	this->Close();
}


